<template>
  <div class="treeBox">
    <a-input-search style="margin-bottom: 8px" placeholder="搜索分组名称" @search="handSearch" />
    <a-tree
      class="warehouseTree"
      ref="warehouseTree"
      :tree-data="treeData"
      blockNode
      :replaceFields="{
        key: 'id',
        children: 'children'
      }"
      :expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      @expand="onExpand"
      :selectedKeys.sycn="selectedKeys"
      @select="onSelect"
    >
      <template slot="customtitle" slot-scope="item">
        <div class="disFlxJS">
          <div class="ov-1" style="display: unset;">
            <span v-if="item.name.indexOf(searchValue) > -1">
              {{ item.name.substr(0, item.name.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ item.name.substr(item.name.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ item.name }}</span>
            <span>（{{ item.groupNumber }}）</span>
          </div>
          <div v-if="!hideOperate && item.id >= 0" v-has="'content:warehouse:editGroup'" class="disFlxAC hoverShow">
            <div class="_pl-5 _pr-5" @click.stop="openEditGroup(item)">
              <a-icon type="edit" />
            </div>
            <div class="_pl-5 _pr-5" @click.stop="handDelete(item)">
              <a-icon type="delete" />
            </div>
          </div>
        </div>
      </template>
    </a-tree>
    <div class="disFlxCC _pt-5">
      <a-button v-has="'content:warehouse:editGroup'" icon="plus" @click="openEditGroup()">新建分组</a-button>
    </div>

    <EditGroup ref="EditGroup" :activeTabKey="activeTabKey" :treeDataLength="treeData.length" @refresh="getWarehouseGroupList" />
  </div>
</template>

<script>
import { getWarehouseGroup, deleteWarehouseGroup } from '@/api/content/warehouse'
import EditGroup from './editGroup'
import { cloneDeep, uniq } from 'lodash-es'

export default {
  components: {
    EditGroup
  },
  data() {
    return {
      oldTreeData: [], // 初始树形结构
      treeData: [],

      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      selectedKeys: []
    }
  },
  props: {
    activeTabKey: {
      type: String,
      required: true,
      default: ''
    },
    // 是否隐藏操作
    hideOperate: {
      type: Boolean,
      default: false
    }
  },
  watch:{
    activeTabKey: {
      handler () {
        this.getWarehouseGroupList();
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async getWarehouseGroupList() {
      const that = this;
      const { data } = await getWarehouseGroup(that.activeTabKey)
      data.forEach(v => {
        that.$set(v, 'scopedSlots', { title: 'customtitle' })
      })
      that.oldTreeData = that.handleTree(data, 0)
      const ungrouped = data.find(v => v.id === -1) // 未分组
      ungrouped && that.oldTreeData.unshift(ungrouped)

      that.handSearch(that.searchValue);
    },
    handleTree(treeData, parentId) {
      let treeArr = []
      for (let i = 0; i < treeData.length; i++) {
        let item = treeData[i]
        if (item.parentId === parentId) {
          const _children = this.handleTree(treeData, item.id)
          _children.length ? (item.children = _children) : (delete item.children);
          treeArr.push(item);
        }
      }
      return treeArr
    },
    // tree展开&&搜索逻辑 start
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    async handSearch(value) {
      this.searchValue = value
      if (value) {
        this.treeData = await this.searchData(cloneDeep(this.oldTreeData), value)
      } else {
        this.treeData = cloneDeep(this.oldTreeData)
      }
      // 设置默认分组
      if(!this.selectedKeys.length && this.treeData.length){
        this.onSelect([this.treeData[0].id], {selected: true, node: {dataRef: this.treeData[0]}})
      }
    },
    searchData(data, val) {
      const that = this
      return data.filter(function f(o) {
        if (o.name.includes(val)) {
          that.expandedKeys = uniq([...that.expandedKeys, o.id])
          that.autoExpandParent = true
          return true
        }
        if (o.children) {
          return (o.children = o.children.filter(f)).length
        }
      })
    },
    onSelect(selectedKeys, {selected, node}){
      if(selected){
        this.selectedKeys = selectedKeys; // 不允许取消勾选
        this.$emit('onSelect', node.dataRef);
      }
    },
    
    // tree展开&&搜索逻辑 end

    openEditGroup(group) {
      this.$refs.EditGroup.show(group)
    },

    handDelete(group) {
      const that = this;
      that.$confirm({
        title: '确定要删除分组？',
        content: `删除后本分组内的图片也将一起被删除！已使用的场景不受影响`,
        centered: true,
        onOk() {
          return new Promise((resolve, reject) => {
            deleteWarehouseGroup(group.id).then((res) => {
              that.getWarehouseGroupList()
              that.selectedKeys = that.selectedKeys.filter(v=> v !== group.id);
              that.$message.success('删除成功!')
              resolve(res)
            }).catch((err)=>{
              reject(err)
            })
          })
        }
      });
    }
  }
}
</script>

<style lang="less" scoped>
.treeBox {
  border-right: solid 1px #f5f5f5;
  padding: 10px;
}
.warehouseTree {
  width: 220px;
}
.warehouseTree /deep/ li > span {
  line-height: 32px;
  height: 32px;
}
.warehouseTree /deep/ li > span.ant-tree-node-content-wrapper {
  display: inline-block;
  width: calc(100% - 24px);
}

.hoverShow{
  display: none;
}
.disFlxJS:hover .hoverShow{
  display: flex;
}
</style>
